//
//  UIColorUtils.swift
//
//  Created by IOS-User on 2017/4/3.
//  Copyright © 2017年 IOS-User. All rights reserved.
//

import UIKit

/**
 * UIColor 扩展(类似OC 的分类)
 */
extension UIColor {

    /**
     * 获取颜色
     * @parameter hex:#开头字符串("#ffffff")
     * @return UIColor
     */
    func colorFromHexString(hex:String) -> UIColor {

        var strTemp = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

        if strTemp.hasPrefix("#") {
           strTemp = NSString.init(string: strTemp).substring(from: 1)
        }

        if strTemp.count != 6 {
            if #available(iOS 13.0, *) {
                let _tc = UIColor.init { (trainCollection:UITraitCollection) -> UIColor in
                    if trainCollection.userInterfaceStyle == .dark {
                        return UIColor.white
                    }
                    return UIColor.gray
                }
                return _tc
            }
            
            return UIColor.gray
        }

        let rStr:String = NSString.init(string: strTemp).substring(to: 2)
        let gStr:String = (NSString.init(string: strTemp).substring(from: 2) as NSString).substring(to: 2)
        let bStr:String = NSString.init(string: strTemp).substring(from: 4)

        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner.init(string: rStr).scanHexInt32(&r)
        Scanner.init(string: gStr).scanHexInt32(&g)
        Scanner.init(string: bStr).scanHexInt32(&b)

        let tc = UIColor.init(red: CGFloat.init(r)/255.0,
                              green: CGFloat.init(g)/255.0,
                              blue: CGFloat.init(b)/255.0,
                              alpha: 1)
        
        if #available(iOS 13.0, *) {
            let _tc = UIColor.init { (trainCollection:UITraitCollection) -> UIColor in
                if trainCollection.userInterfaceStyle == .dark {
                    return UIColor.white
                }
                return tc
            }
            return _tc
        }
        return tc
    }

    /**
     * 获取颜色
     * @parameter hex:十六进制 0xffffff
     * @return UIColor
     */
    func colorFromHexInt(hex:Int,alpha:CGFloat = CGFloat.init(1)) -> UIColor {

        return UIColor.init(red: CGFloat.init((hex & 0xFF0000) >> 16) / 255.0,
                            green: CGFloat.init((hex & 0xFF00) >> 8) / 255.0,
                            blue: CGFloat.init(hex & 0xFF) / 255.0,
                            alpha: alpha)
    }
    
    /**
     * 获取颜色
     * @para r CGFloat
     * @para g CGFloat
     * @para b CGFloat
     *
     * @return UIColor
     */
    func colorFromHexRGB(r:CGFloat,g:CGFloat,b:CGFloat,alpha:CGFloat = 1) -> UIColor {
        return UIColor.init(red: r / 255.0,
                            green: g / 255.0,
                            blue: b / 255.0,
                            alpha: alpha)
    }
    
}
